//
//  InvoiceViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2017/10/26.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "InvoiceViewController.h"
#import "InvoiceCell.h"
#import "InvoiceCellI.h"
#import "InvoiceIICell.h"
#import "WWebViewController.h"
#import "ReportVideoModel.h"
#import "SchoolListViewController.h"
#import "VideoDetailViewController.h"
#import "InvoiceModel.h"
#import "WTabBar.h"
#import "UIImageView+WebCache.h"
#import "CheckNetwork.h"

@interface InvoiceViewController ()<UITableViewDataSource, UITableViewDelegate,InvoiceCellDelegate,InvoiceCellIDelegate,InvoiceIICellDelegate> {
    NSString *strMark;
}

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *arrTrain;
@property (nonatomic, strong)NSMutableArray *arrInvocie;

@end

@implementation InvoiceViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    if ([WShareUtil sharedData].dicSleSymbol) {
        if ([[WShareUtil sharedData].dicSleSymbol[@"symbol"] isEqualToString:Invoice_Symbol]) {
            for (int i = 0; i < self.arrTrain.count; i++) {
                if ([[WShareUtil sharedData].dicSleSymbol[@"id"] isEqualToString:[self.arrTrain[i] strId]]) {

                    ReportVideoModel *videoModel = self.arrTrain[i];
                    if ([[WShareUtil sharedData].dicSleSymbol[@"chosen"] boolValue]) {
                        videoModel.chosen = @"1";
                    }
                    [self.arrTrain replaceObjectAtIndex:i withObject:videoModel];

                    [self.tableView reloadData];
                    [WShareUtil sharedData].dicSleSymbol = nil;
                }
            }
        }
    }

    if ([WShareUtil sharedData].dicBuySymbol) {
        for (int i = 0; i < self.arrTrain.count; i++) {
            if ([[WShareUtil sharedData].dicBuySymbol[@"id"] isEqualToString:[self.arrTrain[i] strId]]) {

                ReportVideoModel *videoModel = self.arrTrain[i];
                if ([[WShareUtil sharedData].dicBuySymbol[@"boughten"] boolValue]) {
                    videoModel.boughten = @"1";
                }
                [self.arrTrain replaceObjectAtIndex:i withObject:videoModel];

                [self.tableView reloadData];
                [WShareUtil sharedData].dicBuySymbol = nil;
            }
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _arrTrain = [NSMutableArray array];
    _arrInvocie = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    [self.tableView.superview insertSubview:[UIView new] atIndex:0];

    [self invoiceVcDataVideoRequest];
    [self hotVcKPWBDataRequest:@"csqk"];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noWifiRefershingEnd) name:NOREFRESH object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyRequestListData) name:HOME_INVOICE_NOTIFY object:nil];

}

- (void)noWifiRefershingEnd {
    [self.tableView.header endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;
}

- (void)notifyRequestListData{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self invoiceVcDataVideoRequest];
    }];
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        
        if (XIPHONE) {
//            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64 - 44 - 49 -30) style:UITableViewStylePlain];
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64 + 30, WSCREENH_WIDTH, WSCREENH_HEIGHT -30 - 64) style:UITableViewStylePlain];
        }else{
//            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64 - 44 - 49 ) style:UITableViewStylePlain];
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64) style:UITableViewStylePlain];
        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//去掉横线
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 328;
    } else if (indexPath.section == 1) {
        return 200;
    }
    return 160;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReportCell"];

    if (indexPath.section == 0) {
        if (cell == nil) {
            InvoiceCell  *invoiceCell = [[[NSBundle mainBundle] loadNibNamed:@"InvoiceCell" owner:self options:nil] lastObject];
            invoiceCell.imageLeft.clipsToBounds = YES;
            invoiceCell.imageRight.clipsToBounds = YES;

            if (self.arrTrain && self.arrTrain.count > 0) {
                [invoiceCell.imageLeft sd_setImageWithURL:[NSURL URLWithString:[self.arrTrain[0] imgsrc]] placeholderImage:[UIImage imageNamed:@"invoice_image1.png"]];
                if ([[_arrTrain[0] chosen] boolValue]) {
                    invoiceCell.lbTypeL.hidden = NO;
                    invoiceCell.lbTypeL.text = @"已选课";
                    invoiceCell.lbTypeL.backgroundColor = WRGBColor(235, 107, 12);
                } else if (![[_arrTrain[0] chosen] boolValue] && [[_arrTrain[0] boughten] boolValue]) {
                    invoiceCell.lbTypeL.hidden = NO;
                    invoiceCell.lbTypeL.text = @"已购买";
                    invoiceCell.lbTypeL.backgroundColor = WRGBColor(208, 45, 39);
                }

                [invoiceCell.imageRight sd_setImageWithURL:[NSURL URLWithString:[self.arrTrain[1] imgsrc]] placeholderImage:[UIImage imageNamed:@"invoice_image2.png"]];
                if ([[_arrTrain[1] chosen] boolValue]) {
                    invoiceCell.lbTypeR.hidden = NO;
                    invoiceCell.lbTypeR.text = @"已选课";
                    invoiceCell.lbTypeR.backgroundColor = WRGBColor(235, 107, 12);
                } else if (![[_arrTrain[1] chosen] boolValue] && [[_arrTrain[1] boughten] boolValue]) {
                    invoiceCell.lbTypeR.hidden = NO;
                    invoiceCell.lbTypeR.text = @"已购买";
                    invoiceCell.lbTypeR.backgroundColor = WRGBColor(208, 45, 39);
                }

                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.lineSpacing = 2;// 字体的行间距
                NSDictionary *attributes = @{
                                             NSFontAttributeName:[UIFont systemFontOfSize:14],
                                             NSParagraphStyleAttributeName:paragraphStyle
                                             };
                invoiceCell.textLeft.attributedText = [[NSAttributedString alloc] initWithString:[self.arrTrain[0] strTitle] attributes:attributes];
                invoiceCell.textRight.attributedText = [[NSAttributedString alloc] initWithString:[self.arrTrain[1] strTitle] attributes:attributes];
//                invoiceCell.textLeft.text = [self.arrTrain[0] strTitle];
//                invoiceCell.textRight.text = [self.arrTrain[1] strTitle];
            }

            invoiceCell.delegate = self;
            cell = invoiceCell;
        }
    }else if (indexPath.section == 1) {

        if (cell == nil) {
            InvoiceCellI  *invoiceCellI = [[[NSBundle mainBundle] loadNibNamed:@"InvoiceCellI" owner:self options:nil] lastObject];

            if ([strMark isEqualToString:@"csqk"]) {
                invoiceCellI.btnCleanCard.layer.borderColor = [UIColor redColor].CGColor;
                [invoiceCellI.btnCleanCard setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            }else if ([strMark isEqualToString:@"fpkj"]) {
                invoiceCellI.btnInvocie.layer.borderColor = [UIColor redColor].CGColor;
                [invoiceCellI.btnInvocie setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

            }else if ([strMark isEqualToString:@"hzmx"]) {
                invoiceCellI.btnPrint.layer.borderColor = [UIColor redColor].CGColor;
                [invoiceCellI.btnPrint setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

            }else if ([strMark isEqualToString:@"skkpqt"]) {
                invoiceCellI.btnOther.layer.borderColor = [UIColor redColor].CGColor;
                [invoiceCellI.btnOther setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

            }

            if (self.arrInvocie && self.arrInvocie.count > 0) {
                invoiceCellI.lbTop.text = [self.arrInvocie[0] strTitle];
                invoiceCellI.lbTopTime.text = [self.arrInvocie[0] fbsj];
                invoiceCellI.lbMiddle.text = [self.arrInvocie[1] strTitle];
                invoiceCellI.lbMiddleTime.text = [self.arrInvocie[1] fbsj];
                invoiceCellI.lbBottom.text = [self.arrInvocie[2] strTitle];
                invoiceCellI.lbBottomTime.text = [self.arrInvocie[2] fbsj];
            }
            invoiceCellI.delegate = self;
            cell = invoiceCellI;
        }
    }else if (indexPath.section == 2) {

        if (cell == nil) {
            InvoiceIICell *invoiceIICell = [[[NSBundle mainBundle] loadNibNamed:@"InvoiceIICell" owner:self options:nil] lastObject];
            invoiceIICell.delegate = self;
            cell = invoiceIICell;
        }
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WLog(@"你好");
}

- (void)delegatBtnClick:(UIButton *)button {

    if (button.tag == 1000) {

        CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
        if (![checkNetwork isNetworkReachable]) {//没网
            return;
        } else {
            VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc]init];
            videoDetailVc.strId = @"1001";
            videoDetailVc.symbol = Invoice_Symbol;
            [self.navigationController pushViewController:videoDetailVc animated:YES];
        }
        
    }else if (button.tag == 1001) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"购买设备";
        webVc.shareTitle = @"购买设备";//分享标题
        webVc.strUrl = GMSB_URL;
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 1002) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"安装说明";
        webVc.shareTitle = @"安装说明";//分享标题
        webVc.strUrl = AZSM_URL;
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 2000) {
        SchoolListViewController *listVc = [[SchoolListViewController alloc] init];
        listVc.title = @"在线培训";
        listVc.isInvoiceModelList = YES;
        [self.navigationController pushViewController:listVc animated:YES];
    }else if (button.tag == 2001) {
        
        CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
        if (![checkNetwork isNetworkReachable]) {//没网
            return;
        } else {
            VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc]init];
            if (self.arrTrain && self.arrTrain.count > 0) {
                videoDetailVc.strId = [self.arrTrain[0] strId];
            }
            videoDetailVc.symbol = Invoice_Symbol;
            [self.navigationController pushViewController:videoDetailVc animated:YES];
        }
        
    }else if (button.tag == 2002) {
        
        CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
        if (![checkNetwork isNetworkReachable]) {//没网
            return;
        } else {
            VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc]init];
            if (self.arrTrain && self.arrTrain.count > 0) {
                videoDetailVc.strId = [self.arrTrain[1] strId];
            }
            videoDetailVc.symbol = Invoice_Symbol;
            [self.navigationController pushViewController:videoDetailVc animated:YES];
        }

    }
}

- (void)delegateCellIIBtnClick:(UIButton *)button {
    if (button.tag == 4000) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"发票下载";
        webVc.shareTitle = @"发票下载";//分享标题
        webVc.strUrl = FPXZ_URL;
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 4001) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"发票红冲";
        webVc.shareTitle = @"发票红冲";//分享标题
        webVc.strUrl = FPHC_URL;
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 4002) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"打印交付";
        webVc.shareTitle = @"打印交付";//分享标题
        webVc.strUrl = DYJF_URL;
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 4003) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"清单明细";
        webVc.shareTitle = @"清单明细";//分享标题
        webVc.strUrl = QDMX_URL;
        [self.navigationController pushViewController:webVc animated:YES];
    }

}

- (void)delegateCellIBtnClick:(UIButton *)button {
    if (button.tag == 3000) {
        self.tabBarController.selectedIndex = 2;
        [WShareUtil sharedData].strLevel = @"kp";
        [WShareUtil sharedData].strLevel2 = @"tech";
        [[NSNotificationCenter defaultCenter] postNotificationName:@"dd" object:nil userInfo:@{@"strLevel":@"kp",@"strLevel2":@"tech"}];
        WTabBar *wtabBar = (WTabBar *)self.tabBarController.tabBar;
        [self.navigationController popToRootViewControllerAnimated:YES];
//        [wtabBar.plusBtn setBackgroundImage:[UIImage imageNamed:@"WB_XZ@2x.png"] forState:UIControlStateNormal];
        [wtabBar.plusBtn setImage:[UIImage imageNamed:@"WB_XZ@2x.png"] forState:UIControlStateNormal];
    }else if (button.tag == 3001) {
        [self hotVcKPWBDataRequest:@"csqk"];
    }else if (button.tag == 3002) {
        [self hotVcKPWBDataRequest:@"fpkj"];
    }else if (button.tag == 3003) {
        [self hotVcKPWBDataRequest:@"hzmx"];
    }else if (button.tag == 3004) {
        [self hotVcKPWBDataRequest:@"skkpqt"];
    }else if (button.tag == 3005) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"开票问吧";
        if (self.arrInvocie && self.arrInvocie.count > 0) {
            webVc.shareTitle = [self.arrInvocie[0] strTitle];//分享标题
            webVc.strID = [self.arrInvocie[0] strId];//分享ID
            webVc.strUrl = [self.arrInvocie[0] link];
        }
        webVc.strType = @"wz";//分享类型文章
        
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 3006) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"开票问吧";

        if (self.arrInvocie && self.arrInvocie.count > 0) {
            webVc.shareTitle = [self.arrInvocie[1] strTitle];//分享标题
            webVc.strID = [self.arrInvocie[1] strId];//分享ID
            webVc.strUrl = [self.arrInvocie[1] link];
        }

        webVc.strType = @"wz";//分享类型文章
        
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (button.tag == 3007) {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"开票问吧";

        if (self.arrInvocie && self.arrInvocie.count > 0) {
            webVc.shareTitle = [self.arrInvocie[2] strTitle];//分享标题
            webVc.strID = [self.arrInvocie[2] strId];//分享ID
            webVc.strUrl = [self.arrInvocie[2] link];
        }
    
        webVc.strType = @"wz";//分享类型文章
        [self.navigationController pushViewController:webVc animated:YES];
    }
}

//开票在线培训视频请求
- (void)invoiceVcDataVideoRequest {

    [WShareUtil sharedData].isShowWait = NO;

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"revert":@"list",@"recommend":@"kpzq",@"num":@"2"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        [self.arrTrain removeAllObjects];
        for (NSDictionary *dic in returnDic[@"list"]) {
            ReportVideoModel *videoModel = [ReportVideoModel mj_objectWithKeyValues:dic];
            [self.arrTrain addObject:videoModel];
        }
        [self noWifiRefershingEnd];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self noWifiRefershingEnd];
        WLog(@"失败");
    } showProgress:YES];
}

//开票问吧
- (void)hotVcKPWBDataRequest:(NSString *)paramet {
    strMark = paramet;
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"fwwb",@"content":@{@"revert":@"list",@"level":@"tech",@"level2":@"kp",@"level3":paramet,@"num":@"3"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [self.arrInvocie removeAllObjects];
        for (NSDictionary *dic in returnDic[@"list"]) {
            InvoiceModel *invoiceModel = [InvoiceModel mj_objectWithKeyValues:dic];
            [self.arrInvocie addObject:invoiceModel];
        }
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

@end
